<template>
    <div class="content-main">
        <div class="breadcrumb">
            <div class="breadcrumb-icon">
                <img src="./../../assets/images/breadcrumb_icon.png" />
            </div>
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/teacher/index' }">实训案例</el-breadcrumb-item>
                <el-breadcrumb-item>实训案例制作</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="content-box">
            <div class="search-box">
                <div class="search-item">
                    <span class="search-title">章节名称: </span>
                    <el-select
                        v-model="chapterValue"
                        placeholder="请选择章节"
                        value-key="value"
                        style="float:left;">
                        <el-option
                        v-for="item in chapterStatus"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                </div>
                <div class="search-item">
                    <span class="search-title">类型: </span>
                    <el-select
                        v-model="typeValue"
                        placeholder="请选择类型"
                        value-key="value"
                        style="float:left;">
                        <el-option
                        v-for="item in typeStatus"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                </div>
                <div class="search-item">
                    <el-button type="primary" @click="searchFn">搜索</el-button>
                </div>
                <div class="search-item" style="float:right; margin: 0 0 0 10px;">
                    <el-dropdown @command="handleCommand">
                        <el-button type="primary">
                            更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown" >
                            <el-dropdown-item command="a"><a :href="'/dataplatform/chapter/excelDownload?itemId='+projectId">流程下载</a></el-dropdown-item>
                            <el-dropdown-item command="flowUpload">流程上传</el-dropdown-item>
                            <el-dropdown-item command="order">调整顺序</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </div>
                <div class="search-item" style="float:right; margin: 0 0 0 10px;">
                    <el-button type="primary" @click="deleteList">批量删除</el-button>
                </div>
                <div class="search-item" style="float:right; margin:0;">
                    <el-button type="primary" @click="addChapter(1)">添加章节</el-button>
                </div>
            </div>
            <div class="teaching-mgt-tips">
                <span>提示: </span>
                1. 删除章节或步骤后，系统会自动删除实训说明等信息，请谨慎操作。
            </div>
            <div class="table-content" v-loading="tableLoading">
                <el-table
                :data="tableData"
                ref="multipleTable"
                border
                style="width: 100%"
                @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="100">
                    </el-table-column>
                    <el-table-column prop="name" label="章节名称">
                    </el-table-column>
                    <el-table-column prop="typeName" label="类型">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button v-if="scope.row.type == 1" type="text" @click="stepFn(scope.row.id,2)">维护实训步骤</el-button>
                            <el-button type="text" @click="editorChapter(2,scope.row.id, scope.row.name, scope.row.type, scope.row.target)">编辑章节</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-size="pagesize"
                    layout="total, prev, pager, next, jumper"
                    :total="totalCount"
                    style="margin-top: 20px; text-align: center;">
                </el-pagination>
            </div>
        </div>
        <el-dialog :title="chapterTitle" :visible.sync="dialogFormVisible" width="500px">
            <el-form :model="form" :rules="rules" ref="form" label-width="100px">
                <el-form-item label="章节名称 :" prop="chapterName">
                    <el-input type="text" v-model="form.chapterName" style="width: 50%;" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="类型 :" prop="chapterTypeValue">
                    <el-select
                        v-model="form.chapterTypeValue"
                        placeholder="请选择类型"
                        value-key="value"
                        style="float:left;"
                        v-if="chapterTypeStatus">
                        <el-option
                        v-for="item in form.chapterTypeStatus"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                    <span v-else>{{ form.chapterTypeValue }}</span>
                </el-form-item>
                <el-form-item label="章节目标 :" prop="chapterAims">
                    <el-input type="textarea" v-model="form.chapterAims" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align:center;">
                <el-button type="primary" @click="submitForm('form')">保存</el-button>
            </div>
        </el-dialog>
        <el-dialog class="adjustment-order-dialog" title="调整顺序" :visible.sync="dialogFormVisible2" width="500px">
            <div class="adjustment-order-content">
                <SortableList axis="y" lockAxis="y" v-model="treeItems">
                    <SortableItem v-for="(item, index) in treeItems" :index="index" :key="index" :item="item.label"/>
                </SortableList>
            </div>
            <div slot="footer" class="dialog-footer" style="text-align:center;">
                <el-button type="primary" @click="submit()">确定</el-button>
            </div>
        </el-dialog>
        <el-dialog class="common-tool-dialog" title="流程上传" :visible.sync="dialogFormVisible3">
            <el-form :model="form2" :rules="rules2" ref="form2" label-width="100px">
                <el-form-item label="文件上传 :" prop="versionFile" class="version-file">
                    <el-button type="primary">上传文件<input type="file" multiple="multiple" auto-complete="off" @change="getFile"></input></el-button>
                    <p v-if="form2.versionFile.length>0">已选: {{form2.versionFile}}</p>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align:center;">
                <el-button type="primary" @click="saveForm('form2')">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { ContainerMixin, ElementMixin } from 'vue-slicksort'
    const SortableList = {
        mixins: [ContainerMixin],
        template: `
            <ul class="list">
            <slot />
            </ul>
        `,
    }

    const SortableItem = {
        mixins: [ElementMixin],
        props: ['item'],
        template: `
            <li class="list-item" style="z-index:10000; margin: 0 20px; background:#fff; padding: 20px; list-style:none;">{{item}}</li>
        `,
    }
    export default {
        components: {
            SortableItem,
            SortableList,
        },
        data () {
            return {
                projectId: '',
                chapterStatus: [
                    {
                        value: '',
                        label: '全部'
                    }
                ],
                chapterValue: '',
                typeStatus: [
                    {
                        value: '',
                        label: '全部'
                    },
                    {
                        value: 1,
                        label: '预置样例'
                    },
                    {
                        value: 2,
                        label: '学生实训'
                    }
                ],
                typeValue: '',
                tableLoading: false,
                tableData: [
                    {
                        toolsTitle: 'assd',
                        toolsName: '111'
                    }
                ],
                currentPage:1,
                pagesize:10,
                totalCount: 1000,
                multipleSelection: [],
                dialogFormVisible: false,
                form: {
                    chapterName: '',
                    chapterTypeStatus: [
                        {
                            value: 1,
                            label: '预置样例'
                        },
                        {
                            value: 2,
                            label: '学生实训'
                        }
                    ],
                    chapterTypeValue: '',
                    chapterAims: ''
                },
                rules: {
                    chapterName: [
                        { required: true, message: '请输入章节名称', trigger: 'blur' }
					],
                    chapterTypeValue: [
                        { required: true, message: '请选择类型', trigger: 'blur' }
					],
					chapterAims: [
                        { required: true, message: '请输入章节目标', trigger: 'blur' }
                    ]
                },
                chapterTitle: '',
                addOrEditorStatus: '',
                editorChapterId: '',
                chapterTypeStatus: true,
                dialogFormVisible2: false,
                treeItems: [],
                dialogFormVisible3: false,
                form2: {
                    fileName: '',
                    versionFile: ''
                },
                rules2: {
                    versionFile: [
                        { required: true, message: '请上传文件', trigger: 'blur' }
					]
                }
            }
        },
        created () {
            this.projectId = JSON.parse(window.localStorage.getItem('teacher-project-id')).itemId
            this.init()
            this.listTable()
        },
        methods: {
            init(){
                let self = this
                self.$http.get('/dataplatform/chapter/search/listChapterName?itemId='+self.projectId).then(response => {
                    let res = response.data
                    if(res.code == '200'){
                        for (let i = 0; i < res.data.length; i++) {
                            let classListJson = {}
                            classListJson.label = res.data[i].name
                            classListJson.value = res.data[i].id
                            self.chapterStatus.push(classListJson)
                        }
                    }else if(res.code == '401'){
                        self.$router.replace({
                            path:'/login'
                        })
                    }else{
                        self.$message.error(res.message)
                    }
                })
            },
            listTable(){
                let self = this
                self.$http.get('/dataplatform/chapter/page?pageNum='+self.currentPage+'&pageSize='+self.pagesize+'&itemId='+self.projectId+'&chapterId='+self.chapterValue+'&type='+self.typeValue).then(response => {
                    let res = response.data
                    if(res.code == '200'){
                        self.tableData = res.data.list
                        self.totalCount = res.data.total
                    }else if(res.code == '401'){
                        self.$router.replace({
                            path:'/login'
                        })
                    }else{
                        self.$message.error(res.message)
                    }
                })
            },
            handleCommand(command) {
                let self = this
                if(command == 'order'){
                    self.adjustOrder()
                }else if(command == 'download'){
                    self.downloadFn()
                }else if(command == 'flowUpload'){
                    self.dialogFormVisible3 = true
                }
            },
            //调整顺序
            adjustOrder(){
                let self = this
                self.$http.get('/dataplatform/chapter/order/ztreeDetail?itemId='+self.projectId).then(response => {
                    let res = response.data
                    if(res.code == '200'){
                        self.treeItems = res.data
                    }else if(res.code == '401'){
                        self.$router.replace({
                            path:'/login'
                        })
                    }else{
                        self.$message.error(res.message)
                    }
                })
                this.dialogFormVisible2 = true
            },
            //调整顺序表单提交
            submit(formName) {
                let self = this
                let chapterIdsArr = []
                for(let i = 0; i < self.treeItems.length; i++){
                    chapterIdsArr.push(self.treeItems[i].id)
                }
                self.$http.post('/dataplatform/chapter/order/update',{
                    itemId: self.projectId,
                    chapterIds: chapterIdsArr
                }).then(response => {
                    let res = response.data
                    if(res.code == '200'){
                        self.$message({
                            message: '调整成功',
                            type: 'success'
                        })
                        self.dialogFormVisible2 = false
                        self.listTable()
                    }else if(res.code == '401'){
                        self.$router.replace({
                            path:'/login'
                        })
                    }else{
                        self.$message.error(res.message)
                    }
                })
            },
            //维护实训步骤
            stepFn(id, type){
                this.$router.push({
                    path: '/teacher/projectTrainingStep',
                    query: {
                        stepId: id,
                        type: type
                    }
                })
            },
            //表格分页
			handleSizeChange: function (size) {
				this.pagesize = size;
			},
			handleCurrentChange: function(currentPage) {
				this.currentPage = currentPage
				this.listTable()
            },
            //全选
			handleSelectionChange(val) {
				let valArr = []
				for(let i = 0; i < val.length; i++){
					valArr.push(val[i].id)
				}
				this.multipleSelection = valArr
            },
            //搜索
            searchFn(){
                this.currentPage = 1
                this.listTable()
            },
            //删除选中
			deleteList() {
				let self = this;
				if(self.multipleSelection.length == 0){
                    self.$message({
                        message: '请选择要删除的章节',
                        type: 'warning'
                    })
					return
                }
                let ids = ''
				for(let item in self.multipleSelection){
					if(item == 0){
						ids = self.multipleSelection[item]
					}else{
						ids = ids + ',' +self.multipleSelection[item]
                    }
                }
				self.$confirm('是否删除选中?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					self.$http.get('/dataplatform/chapter/delete?ids='+ids+'').then((response) => {
						let res = response.data;
						if(res.code == '200'){
                            self.$message({
                                message: '删除成功',
                                type: 'success'
                            })
                            self.currentPage = 1
							self.listTable()
						}else if(res.code == '401'){
                            self.$router.replace({
                                path:'/login'
                            })
                        }else{
                            self.$message.error(res.message)
                        }
					},(err) => {
						console.log('err');
					})
				}).catch(() => {
				});
            },
            //添加章节
            addChapter(type){
                this.addOrEditorStatus = type
                this.chapterTypeStatus = true
                this.chapterTitle = '添加章节'
                this.form.chapterName = ''
                this.form.chapterTypeValue = ''
                this.form.chapterAims = ''
                this.dialogFormVisible = true

            },
            //編輯章節
            editorChapter(type, id, name, typeId, target){
                this.addOrEditorStatus = type
                this.chapterTypeStatus = false
                this.chapterTitle = '编辑章节'
                this.editorChapterId = id
                this.form.chapterName = name
                this.form.chapterTypeValue = typeId
                this.form.chapterAims = target
                this.dialogFormVisible = true
            },
            //添加章节表单提交
            submitForm(form) {
                let self = this
                self.$refs[form].validate((valid) => {
                    if (valid) {
                        let data = {}, url
                        if(self.addOrEditorStatus == 1){
                            url = '/dataplatform/chapter/create'
                            data = {
                                itemId: self.projectId,
                                name: self.form.chapterName,
                                type: self.form.chapterTypeValue,
                                target: self.form.chapterAims
                            }
                        }else if(self.addOrEditorStatus == 2){
                            url = '/dataplatform/chapter/update'
                            data = {
                                id: self.editorChapterId,
                                name: self.form.chapterName,
                                target: self.form.chapterAims
                            }
                        }
                        self.$http.post(url,data).then(response => {
                            let res = response.data
                            if(res.code == '200'){
                                if(self.addOrEditorStatus == 1){
                                    self.$message({
                                        message: '添加成功',
                                        type: 'success'
                                    })
                                }else if(self.addOrEditorStatus == 2){
                                    self.$message({
                                        message: '編輯成功',
                                        type: 'success'
                                    })
                                }
                                self.dialogFormVisible = false
                                self.listTable()
                                self.$refs[form].resetFields()
                            }else if(res.code == '401'){
                                self.$router.replace({
                                    path:'/login'
                                })
                            }else{
                                self.$message.error(res.message)
                            }
                        })
                    }
                })
            },
            //上传文件
            getFile($event) {
                let fileType = $event.target.files[0].name
                    fileType = fileType.substring((fileType.lastIndexOf('.') + 1), fileType.length)
                if(fileType != 'xls' && fileType != ".xlsx"){
                    this.$message.error('请上传Excel文件!')
                    return
                }
                this.form2.fileName = $event.target.files[0]
                this.form2.versionFile = $event.target.files[0].name
            },
            //上传文件表单提交
            saveForm(form2) {
                let self = this
                console.log(self.form2.fileName)
                let formData = new FormData()
                    formData.append('file', self.form2.fileName);
                    formData.append('itemId', self.projectId);
				self.$refs[form2].validate((valid) => {
                    if (valid) {
                        self.$http.post('/dataplatform/chapter/excelUpload', formData, {headers: {'Content-Type': 'multipart/form-data'}}).then((response) => {
                            let res = response.data
                            if(res.code == '200') {
                                self.$message({
                                    message: '上传成功',
                                    type: 'success'
                                })
                                self.dialogFormVisible3 = false
                                self.$refs[form2].resetFields()
                                self.listTable()
                            }else if(res.code == '401'){
                                self.$router.replace({
                                    path:'/login'
                                })
                            }else{
                                self.$message.error(res.message)
                            }
                        })
                    }
                })
            }
        }
    }
</script>

<style lang="scss" >
    .el-tree{
        .el-tree-node__expand-icon{
            background: url('./../../assets/images/tree_icon.png') no-repeat 5px 5px;
        }
    }
</style>

